﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Windows.Forms;
using AT_UHF_NET;

namespace ceTerm
{
    public partial class StokKabul : XForm
    {

        int barcode = -1;

        DataTable dtVendor = null;
        List<string> tags = new List<string>();

        public StokKabul()
        {
            InitializeComponent();

            pnlSinyalGucu.Visible = false;
            this.WindowState = FormWindowState.Maximized;
            this.KeyPreview = true;

            Terminal.SetActivatedForm(this);

            dtVendor = Main.ceWS.GetUreticiler(Main.Password);
            foreach (DataRow dr in dtVendor.Rows)
                cmbUretici.Items.Add(new Vendor((int)dr["VendorId"], dr["Name"].ToString()));
        }

        private void ShowInfo(string info)
        {
            lblStatus.Text = info;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F18: // AT570, AT870 Gun Trigger 
                case Keys.F19: // AT570, AT870 Gun Trigger 
                    Terminal.StartBarcode();
                    break;
                default:
                    break;
            }

            base.OnKeyDown(e);
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F18: // AT570, AT870 Gun Trigger 
                case Keys.F19: // AT570, AT870 Gun Trigger 
                    Terminal.StopBarcode();
                    break;

                default:
                    break;
            }
            base.OnKeyUp(e);
        }

        //Read Events
        public override void GetReply(string Reply)
        {
            switch (action)
            {
                case Action.Write:
                    action = Action.IDLE;
                    if (tags.Count == 0)
                    {
                        ShowInfo("Ortamda RFID etiket yok, yazılamadı !");
                        Terminal.PlayFail();
                    }
                    else if (tags.Count > 1)
                    {
                        ShowInfo("Ortamda birden fazla (" + tags.Count + ") RFID etiket var, yazılamadı !");
                        Terminal.PlayFail();
                    }
                    else
                        WriteTag();

                    break;
                default:
                    ShowInfo(Reply);
                    break;
            }
        }

        //On Barcode Read
        int preRollId = -1;
        public override void OnScaned(string BarcodeValue, string TypeName, string TypeID)
        {
            string orjBarkod = BarcodeValue;
            Terminal.StopBarcode();
            CleanBarcode(ref BarcodeValue, TypeName);

            //UPC A : raf etiketi tipi
            Int64 vendorRollId = 0;

            bool UreticiBarkodu = (TypeName == "Code 39" || TypeName == "Code 128" || TypeName == "Code 128 / ISBT 128" || TypeName == "Interleaved 2 of 5");

            if (UreticiBarkodu) 
                vendorRollId = int64Parse(BarcodeValue.Trim());
            else
            {
                barcode = intParse(BarcodeValue.Trim());
                if (barcode < 1)
                    return;
            }


            
            try
            {

                if (BarkodTipi(barcode) == barkodTipleri.RafAraba &&  !UreticiBarkodu )
                {
                    barcode -= (int)1e9;
                    DataRow dr = null;

                    try
                    {
                        dr = Main.ceWS.GetRafDetay(Main.Password,barcode).Rows[0];
                        if ((string)dr["Tip"] != "R")
                            return;

                        Shelf = (string)dr["Name"];
                        ShelfId = (int)dr["ShelfId"];
                        lblRaf.Text = Shelf;

                        Terminal.Scanner.Vibrator(true);
                        Thread.Sleep(500);
                        Terminal.PlaySuccess();
                        Terminal.Scanner.Vibrator(false);
                    }
                    catch (Exception ex)
                    {
                        ShowException("Veritabanı hatası!", "Hata", ex);
                        return;
                    }
                }

                else if (UreticiBarkodu)
                {
                    if (cmbUretici.SelectedIndex < 0)
                    {
                        ShowInfo("Önce üretici seçmelisiniz.");
                        Terminal.PlayFail();
                        return;
                    }

                    if (lblRaf.Text == "-")
                    {
                        Terminal.PlayFail();
                        ShowInfo("Önce rafı okutmalısınız.");
                        return;
                    }

                    DataTable dt = Main.ceWS.GetPreRoll(Main.Password,orjBarkod, ((Vendor)cmbUretici.SelectedItem).VendorId);                              

                    if (dt.Rows.Count == 0)
                    {
                        ShowInfo("Bu top listede yok!");
                        return;
                    }

                    int newRollId = (int)dt.Rows[0]["RollId"];
                    preRollId = (int)dt.Rows[0]["PreRollId"];

                    if (newRollId > -1)
                    {
                        ProcessTop(newRollId);
                    }
                    else
                    {
                        Terminal.PlayFail();
                    }
                }
            }
            catch (Exception ex)
            {
                
                ShowException(ex);
            }
        }

        //On RFID Read
        public override void GetAccessEPC(string EPC)
        {
            string[] temp = EPC.Split(",".ToCharArray());
            EPC = temp[0].Substring(4, temp[0].Length - 4);
            int EPCint = intParse(EPC);

            if (EPCint < 4e9)
                EPC = EPCint.ToString();
            if (tags.IndexOf(EPC) < 0)
                tags.Add(EPC);
        }


        private void ProcessTop(int TopId)
        {
            tags.Clear();
            barcode = TopId;

            Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.ACCESS_EPC, true);
            Terminal.RFID.SET_PowerControl((uint)Settings.Power.Yazma/*OkumaMax*/);   //GetReply ı çağırır
            Terminal.StartRFID();   //GetReply ı çağırır
            timer.Interval = (int)Settings.OkumaSuresiMs;
            timer.Enabled = true;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            timer.Enabled = false;
            Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.ACCESS_EPC, false);

            action = Action.Write;
            Terminal.RFID.Stop();   //GetReply ı çağırır
        }

        int ShelfId = 0;
        string Shelf = string.Empty;
        private void WriteTag()
        {
            try
            {
                Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, true);
                Terminal.RFID.SET_PowerControl((uint)Settings.Power.Yazma);   //GetReply ı çağırır

                AccessResult ar = Terminal.WriteRFID2(barcode);
                if (ar == AccessResult.OK)
                {
                    string ret = Terminal.RFID.GET_LAST_ERROR();
                    if (ret == "Success")
                    {
                        Main.ceWS.UpdPreRoll(Main.Password,preRollId, ShelfId);

                        SetButtonsStatus(this, false);

                        ShowInfo("RFID etikete yazıldı.");
                        Terminal.PlaySuccess();

                        lblTop.Text = String.Format("{0:#,###}", barcode);
                    }
                    else
                    {
                        ShowInfo("Etikete yazılamadı. (" + ret + ")");
                        Terminal.PlayFail();
                    }
                }
                else
                {
                    ShowInfo("Etikete yazılamadı. (" + ar.ToString() + ")");
                    Terminal.PlayFail();
                }
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
            finally
            {
                SetButtonsStatus(this, true);
                Terminal.RFID.SET_ReportMode(AT_UHF_NET.ReportMode.WAIT_DONE, false);
            }

        }
    }

    public class Vendor
    {
        public int VendorId;
        public string Name;

        public override string ToString()
        {
            return Name.ToString();
        }

        public Vendor(int VendorId, string Name)
        {
            this.Name = Name;
            this.VendorId = VendorId;
        }
    }
}